/*
 * @name: 
 * @version: 1.1.1
 * @Author: 刘大可
 * @Date: 2022-06-15 09:55:53
 * @LastEditors: 刘大可
 * @LastEditTime: 2023-10-20 11:09:11
 */
var app = getApp();

module.exports = {

    data: {
        formData: {
        },
        amount: 0, // 实际金额 由后台计算
        user_price: 0, // 用户输入金额
        unique: "",
        express_info: [

        ],
        specs: [],
        start: "",
        u: {
            name: "",
            phone: ""
        },
        rider: {},
        food_money: 0,
        storeCoupon: {},
        showRider: false,
        add_price:0,
        start_fee:"",
        storeCouponNums:0,
        platformCouponNums :0,
        isShowAll:false,
        storeLingCouponNums:0,
        ptCouponNums:0, // 平台可领
        ptKyCouponNums:0, //平台可用
        itemss:[
            { value: '0', name: "不需要" },
            { value: '1', name: "需要" }
        ],
        isCan:0,
        multiIndexs:[0,0]
    },
    watch: {
        express_num(val) {
            if (this.userInfo.is_vip == 1) {
                var totals = (this.form.total - this.form.MinRunPrice).toFixed(2);
            } else {
                var totals = this.form.total;
            }
            if (totals < this.form.y_money) {
                this.form.y_money = 0.00
                this.y_money = 0.00
                this.form.co_title = ""
                this.form.co_id = ""
            }
            // this.calculate()
        },
        weightindex(val) {
            this.calculate()
        },
      
        form(val) {
            // console.log("val");
            // console.log(val);
            // 如果用户的价格等于-1 就把基础费给他
            console.log(this.userInfo.is_vip);
            if ((this.type == 3 && this.total_prices != 0) || this.type != 3) {
                this.calculate()
            }
            // console.log(this);
            // console.log(this.$refs);
            // if (this.userInfo) {
            //     if (this.user_price == 0) {
            //         if (this.userInfo.is_vip == 0) {
            //             this.user_price = val.MinRunPrice
            //         }
            //     }
            // }


        },

        user_price(val) {
            this.custom = val
            this.calculate()
        },
        /**
         * 
         * @param {*} val 
         */
        total_prices(val) {
            // this.custom = val
            this.calculate()
        },
        express_info: {

            handler(val) {
                console.log(val)
                this.calculate()
            },
            // 这里是关键，代表递归监听 demo 的变化
            deep: true

        },
        // user_price(e){
        //     console.log(e.toFixed(2));
        // }


    },

    _methods: {

        radioChangeCan(e){
            this.isCan = e.detail.value
            this.jise()
        },
        changeIsShowAll(e) {
            this.isShowAll = !this.isShowAll;

        },
        openLingStore() {
            if (uni.getStorageSync('token')) {
                this.$refs.coupon.showModal();
            }
            // this.getStoreLingComment();

        },

        async getStoreLingComment(pay = 0, unique) {
            let res = await this.request("UserCoupon/wxreceive", {
                store_id: this.bid
            });
            this.storeLingCouponNums = res.data.data.coupon;
            console.log(`------------------------------`);
            console.log(res);
            console.log(`------------------------------`);
        },
        async getStoreComment(pay = 0, unique) {
            // 商家可用
            let res = await this.request("UserCoupon/comcont", {
                pay,
                store_id: this.bid
            });
            this.$refs.coupon.getCouponList()
            this.storeCouponNums = res.data.data.coupon;
       
            console.log(`------------------------------`);
            console.log(res);
            console.log(`------------------------------`);
        },
        // 平台可用
        async getPlatformComment(pay = 0, unique) {
           
            let res = await this.request(
                "UserCoupon/index",
                {
                   
                     s_id: uni.getStorageSync('schoolId'),
                    use_status: 0
                }).then(res=>{
                    // this.platformCouponNums = res.data.data.coupon;
                    if (res.data.data) {
                        this.ptKyCouponNums = res.data.data.length
                    }
                });

           


            // this.request(
            //     "UserCoupon/wxcomcont" 
            //     ,{
            //     pay
            // }).then(res=>{
            //     console.log('res',res);
            //     this.ptKyCouponNums = res.data.data.coupon
            // });

            this.request(
               'UserCoupon/couponindex',{
                s_id: uni.getStorageSync('schoolId'),
            }).then(res => {
                console.log('res', res);
                if (res.data.data) {
                    this.ptCouponNums = res.data.data.length

                }
            });
           
            // this.request(
            //     "UserCoupon/collectable", {
            //     pay
            // }).then(res => {
            //     console.log('res', res);
            //     this.ptCouponNums = res.data.data.coupon
            // });
        },
        lingUnion() {
            uni.navigateTo({
                url: '/gc_school/pages/cupon/index?type=1'
            });
        },
        async getTimeIsPlance(e){
            console.log(e);
            let res=await this.request("Orders/getIsTime",{
                seize_orders_time:(this.tlist[0][e[0]] + ' ' + this.tlist[1][e[1]]),
                s_id: this.school.s_id
            })
            console.log(res);
            if (res.data.msg!="选择成功") {
                this.tips.error(res.data.msg)
            }

            
        },
        enterAddPrice(e) {
            console.log(e);
            // if (this.add_price) {
            // }
            if (parseFloat(this.add_price || 0)<0) {
                this.tips.tips("输入金额有误")
                this.add_price=0
            }
            this.user_price = (parseFloat(this.add_price || 0) + (parseFloat(this.start_fee) || 0)).toFixed(2);

            // this.add_price=""
            // this.setData({
            //     form: { ...this.form, total: this.user_price }
            // });
            this.hideModals(e);
        },
        makecall(phoneNumber) {
            console.log(phoneNumber);
            uni.makePhoneCall({
                phoneNumber
            });
        },
        selectStoreCounper() {
            uni.$once('selectCounper', (data) => {
                console.log(data);
                this.storeCoupon = data;
                this.calculate();
            });
            uni.navigateTo({ url: '/gc_school/pages/store/coupon?store_id=' + this.id + "&price=" + this.food_money });
        },



        selectQiShou() {
            // this.id=1
            // this.rider =  { 
            //     "id": "6", "wxapp_id": "3", 
            //     "s_id": "1", "u_id": "1", 
            //     "openid": "ouMoB5OmtEswYP9YpPsVUoGqhasI", 
            //     "free_time": "10:06-23:00", "price": "3.50", 
            //     "is_upstairs": "1", "speed": "2小时内送达", "label": "", "status": "1", 
            //     "is_auth": "1", "type": "1", "sex": "1", 
            //     "addtime": "2022-12-28 10:07:10",
            //     "date": "2022-12-28", "describes": "很快", 
            //     "avg": "3.67", "have_count": "2", "nickname": "陌年微凉", 
            //     "avatar": "https:\/\/thirdwx.qlogo.cn\/mmopen\/vi_32\/Q0j4TwGTfTIVQxCpuv4yy0icYmnNh56OccuvknFMpQUy3cVjH3l4KKgbhnbj7snD71a2g0A6mG62N5dstMOYiceg\/132", 
            //     "is_top": "1", "order_ing_count": "2", phone: 18239866725}
            uni.$once('selectRider', (data) => {
                console.log(data);
                this.rider = data;
                this.form.MinRunPrice = data.price;
                this.user_price = data.price;
                console.log(this.rider);
                this.showRider = false;

            });
            if (!this.rider.id) {
                // uni.navigateTo({ url: '/gc_school/pages/rider/index?type='+this.type })
                this.showRider = true;
            }

        },
        addForm(init = 0) {
            let index = 0;
            let item = this.specs[index];
            let data = {
                specs: item.name,
                regular:item.id,
                specsIndex: index,
                "price": item.price,
                "code": "",
                point_index: 0,
                qu_id: this.point[0]?.title
            };
            if (init == 1) {
                this.express_info = [data];
            } else {
                this.express_info.push(data);
            }
        },
        changeExpress(e) {
            console.log(e);
            let index = e.currentTarget.dataset.index;
            let item = this.specs[e.detail.value];
            console.log(index);
            console.log(item);

            this.express_info[index].price = item.price;
            this.express_info[index].specs = item.name;
            this.express_info[index].regular = item.id;

          
            this.express_info[index].specsIndex = e.detail.value;
        
        },
        jia(index) {
            let item = this.express_info[index];
            item.price = (Number(item.price) + 1).toFixed(2);

        },
        jian(index) {
            let item = this.express_info[index];
            let price = (Number(item.price) - 1).toFixed(2);
            console.log(price);

            if (price < Number(this.specs[item.specsIndex].price)) {
                // this.tips.tips("你减个Der!")
                // this.tips.tips("不能再减了┭┮﹏┭┮!")
                this.tips.tips("不能再减了!");
            } else {
                item.price = price;

            }
        },
        checkPrice(e) {

            let index = e.currentTarget.dataset.index;
            let price = e.detail.value;
            let i = this.express_info[index].specsIndex;
            let item = this.specs[i];

            if (price < item.price) {
                this.tips.tips("输入价格低于初始价格");
                this.express_info[index].price = item.price;
            }

        },
        del(index) {
            this.express_info.splice(index);
        },
        /**
         * @name 调用接口计算价格
         */
        async calculate() {
            var goods_det = uni.getStorageSync('json');
            let express_info = "";
            if (this.type == 1 | this.type == 2) {
                express_info = JSON.stringify(this.express_info);
            }


            let res = await this.request(this.psType == 0 ? "RenIndex/calculatePriceNew" : 'RenIndex/self_calculatePrice', {
                // let res=await this.request('RenIndex/calculatePrice', {
                s_id: uni.getStorageSync('schoolId'),
                weight: this.weightindex,
                u_id: uni.getStorageSync('u_id'),
                // weight: this.weight[this.weightindex],
                module_id: uni.getStorageSync('module_id'),
                express_num: this.express_num,
                is_vip: this.userInfo.is_vip,
                input_price: this.user_price,
                y_money: this.y_money,
                food_money: this.total_prices || 0,
                store_id: this.bid || "",
                goods_det: JSON.stringify(goods_det),
                express_info,
                store_co_id: this.storeCoupon.id,
                MinRunPrice: this.form.MinRunPrice,
                co_id:this.form.co_id
                // openid: uni.getStorageSync('openid') ? uni.getStorageSync('openid') :
                //     'nologinuser'
            });
            console.log(res);
            if (res.data.msg == "优惠券不可用") {
                this.tips.tips(res.data.msg);
                this.form = {
                    ...this.form,
                    co_title: false,
                    y_money: 0,
                    co_id: 0
                };
                // this.form.co_id=""
                this.y_money = 0;
                this.calculate();
            }

            this.amount = res.data.data.t_money;
            this.unique = res.data.data.unique;
            this.food_money = res.data.data.food_money;
            try {
                if (uni.getStorageSync('token')) {
                    this.getStoreComment(res.data.data.food_money, res.data.data.unique);
                    this.getPlatformComment(res.data.data.t_money, res.data.data.unique);
                }
              
            } catch (error) {
            }

            // this.form={
            //     ...this.form,
            //     unique: res.data.data.unique
            // }
        },
        /**
         * @name 关闭弹窗
         * @update 2022年06月15日11:31:34
         * @param {*} e
         * @returns
         */
        hideModal(e) {
            if (this.modalName == 'ChooseModal') {
                console.log('执行这里');

                if (Number(this.form.total) < Number(this.form.MinRunPrice)) {
                    uni.showToast({
                        title: '最少费用是' + this.form.MinRunPrice,
                        icon: 'none'
                    });
                    return;
                    this.setData({
                        form: { ...this.form, total: this.form.MinRunPrice }
                    });
                }
            }
            var mny = /^[0-9]*(\.[0-9]{1,2})?$/;
            if (!mny.test(this.custom)) {

                // this.custom = this.amount
                // this.user_price = this.amount
                this.user_price = zong;
                this.setData({
                    form: { ...this.form, total: zong }
                });
                this.tips.tips('输入金额无效');

                // app.globalData.util.message('输入金额无效！', '', 'error');
                // return false
            }

            console.log('custom', this.custom);
            console.log('最低金额', this.form.MinRunPrice);
            console.log('优惠金额', this.y_money);

            if (this.y_money > this.custom) {
                app.globalData.util.message('金额不可低于优惠券金额', '', 'error');
                return;
            }

            // if (this.custom == undefined) {
            //     app.globalData.util.message('请输入正确的数字', '', 'error');
            //     return;
            // }
            // if (this.custom < 0) {
            //     app.globalData.util.message('输入金额有误', '', 'error');
            //     // return;
            // }
            var zong = Number(Number(this.form.MinRunPrice) + Number(this.extra_price) + Number(this.extra_jian_price)).toFixed(2);
            zong = this.form.MinRunPrice;
            console.log('不低于', zong); // if(Number(this.data.custom)<Number(this.data.form.MinRunPrice))

            if (Number(this.custom) < zong) {
                console.log(this.tips);
                this.user_price = zong;
                this.setData({
                    form: { ...this.form, total: zong }
                });
                this.tips.tips('金额不能低于' + zong);
                // app.globalData.util.message('金额不能低于' + zong, '', 'error');
                // return;
            } else {
                this.setData({
                    form: { ...this.form, total: this.custom }
                });
            }

            this.setData({
                modalName: null
            });
        },

        getuserInfo() {
            var that = this;
            app.globalData.util.request({
                url: 'WechatUser/view',
                data: {},
                success(res) {
                    that.setData({
                        userInfo: res.data.data
                    });
                    if (res.data.data.is_vip == 1) {
                        that.user_price = 0;
                        that.start_fee = 0;
                    }
                    that.u = {
                        phone: res.data.data.phone
                    };
                    // that.getDefaultPrice()
                    console.log('that.type', that.type);

                    if (that.type == 3) {
                        that.jise();
                    } else {
                        that.calculate();
                    }

                }
            }, true);
        },


        async daodian() {
            var self = this;
            var that = this;
            if (this.ddType == 9) {
                console.log(this.date.date("h:i"));
                this.arrival_time = this.date.date("h:i")

            }
            if (!this.u.name) {
                this.tips.tips("请输入姓名");
                return;
            }
			if(!this.u.phone){
				this.tips.tips("请输入手机号");
				return;
			}
            if (self.is_click) {
                self.setData({
                    is_click: false
                });
                app.globalData.util.request({
                    url: 'Orders/userBuy',
                    data: {
                        s_id: uni.getStorageSync('schoolId'),
                        food_money: this.form.guess_prcie,
                        express_num: this.express_num,
                        store_id: uni.getStorageSync('store_id'),
                        remarks: this.form.showText,
                        // qu_latitude: this.buyaddress.location_x ? this.buyaddress.location_x : uni.getStorageSync('city').location.lng,
                        // qu_longitude: this.buyaddress.location_y ? this.buyaddress.location_y : uni.getStorageSync('city').location.lat,
                        qu_addres: this.buyaddress.address,
                        weight: this.weight[this.weightindex],
                        sex_limit: this.sexindex,
                        // start_time: this.storeType == 0 ? (this.tlist[0][this.multiIndex[0]] + ' ' + this.tlist[1][this.multiIndex[1]]) : 0,
                        food_money: this.total_prices,
                        ...this.form,
                        sh_school: uni.getStorageSync('schoolId'),
                        openid: uni.getStorageSync('openid'),
                        out_time_num: this.form.out_time_num,
                        img: this.picList,
                        attach_file: '',
                        // img: img,
                        good_details: this.good_details,
                        goods_list: JSON.stringify(uni.getStorageSync('json')),
                        unique: this.unique,
                        // ordertime: this.timeList[this.ordertime],
                        givetype: this.storeType,
                        arrival_time: that.arrival_time,
                        is_self_lifting: that.psType,
                        sh_name: this.u.name,
                        phone: this.u.phone,
                        is_box: (this.psType == 1 && this.isCan == 0 && this.ddType == 9) ? 9 : 1,
						d_id:this.d_id
                    },

                    success(res) {
                        console.log('1111111', res);

                        if (res.data.msg == '下单成功，无需支付' || res.data.msg == '会员已抵扣') {
                            uni.showToast({
                                title: "下单成功",
                                // icon: 'loading',
                                icon: 'success',
                                duration: 3000
                            });
                            if (res.data.data.order.is_store_delivery == 2) {
                                app.globalData.util.request({
                                    url: 'Orders/StorePrint',
                                    data: {
                                        o_id: res.data.data.order.id
                                    }
                                });
                            }
                            else {
                                app.globalData.util.request({
                                    url: 'MsgSubscribe/toAllRider',
                                    data: {
                                        ordersn: res.data.data.order.ordersn
                                    }
                                });
                            }
                            setTimeout(function () {
                                uni.navigateTo({
                                    url: '/gc_school/pages/order/index?type=1'
                                });
                            }, 2000);
                            // uni.removeStorage({
                            //     key: 'json'
                            // });
                        } else {
                            console.log(res.data.data.ordersn);
                            uni.requestPayment({
								...res.data.data.paydata,
								timeStamp:  res.data.data.paydata.signType == 'RSA' ?  res.data.data.paydata.timeStamp.toString() : res.data.data.paydata.timestamp.toString() ,
                                // timeStamp: res.data.data.paydata.timestamp.toString(),
                                // nonceStr: res.data.data.paydata.nonceStr,
                                // package: res.data.data.paydata.package,
                                // signType: 'MD5',
                                // paySign: res.data.data.paydata.paySign,
                                success: function (resu) {
                                    console.log('success');
                                    console.log(res.data.data);
                                    // app.globalData.util.request({
                                    //     url: 'MsgSubscribe/toAllRider',
                                    //     data: {
                                    //         ordersn: res.data.data.order.ordersn
                                    //     }
                                    // });
                                    setTimeout(function () {
                                        uni.navigateTo({
                                            url: '/gc_school/pages/order/index?type=1'
                                        });
                                    }, 2000);
                                },
                                fail: function (res) {
                                    console.log('fail');
                                }
                            });
                        }
                    },

                    complete() {
                        self.setData({
                            is_click: true
                        });
                    } // fail(e) {
                    //     console.log('弹框1111', e)
                    // }
                }, true);
            } else {
                uni.showToast({
                    title: '请稍后重试...',
                    icon: 'none'
                });
            }
        }
    },
    get methods() {
        return this._methods;
    },
    set methods(value) {
        this._methods = value;
    },

}